package cn.blu10ph.trustshare.core;

import cn.blu10ph.trustshare.constant.Constant;
import cn.blu10ph.trustshare.util.PgpUtil;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * <p> PGPManager </p >
 *
 * @author cxx
 * @date 2024/4/1 22:22
 */
@Slf4j
@Component
public class PGPManager {

    protected static PGPSecretKey secretKey;
    protected static final Map<String, PGPPublicKey> PUBLIC_KEY_CACHE = new HashMap<>();
    protected static final Map<String, String> TRUST_LEVEL_CACHE = new HashMap<>();

    public static PGPSecretKey getSecretKey() {
        return secretKey;
    }

    public static String setSecretKey(PGPSecretKey secretKey) throws Exception {
        PGPManager.secretKey = secretKey;
        PGPPublicKey publicKey = PgpUtil.getPublicKey(secretKey);
        log.debug("init publicKey[{}}:", PgpUtil.getPublicKeyEncode(publicKey));
        String fingerprintStr = PgpUtil.getPublicKeyFingerprint(publicKey);
        log.debug("init fingerprint[{}}:", fingerprintStr);
        PUBLIC_KEY_CACHE.put(fingerprintStr, publicKey);
        TRUST_LEVEL_CACHE.put(fingerprintStr, Constant.TRUST_LEVEL_ULTIMATELY);
        return fingerprintStr;
    }

    public PGPPublicKey getPublicKey(String publicKeyFingerprint){
        return PUBLIC_KEY_CACHE.get(publicKeyFingerprint);
    }

    public void savePublicKey(String publicKeyFingerprint, PGPPublicKey publicKey){
        PUBLIC_KEY_CACHE.put(publicKeyFingerprint, publicKey);
    }

    public void removePublicKey(String publicKeyFingerprint){
        PUBLIC_KEY_CACHE.remove(publicKeyFingerprint);
    }

    public Set<String> getNodeIdByTrustLevel(Set<String> trustLevels){
        Set<String> nodeIds = new HashSet<>();
        TRUST_LEVEL_CACHE.forEach((key,value)->{
            if(trustLevels.contains(value)){
                nodeIds.add(key);
            }
        });
        return nodeIds;
    }

    public String getTrustLevel(String publicKeyFingerprint){
        return TRUST_LEVEL_CACHE.get(publicKeyFingerprint);
    }

    public void setTrustLevel(String publicKeyFingerprint, String trustLevel){
        TRUST_LEVEL_CACHE.put(publicKeyFingerprint, trustLevel);
    }

    public void removeTrustLevel(String publicKeyFingerprint){
        TRUST_LEVEL_CACHE.remove(publicKeyFingerprint);
    }

}
